<template>
  <div >
    <n-card title="订单列表" header>
      <div class="header" >
        <!-- <div>
          <NButton type="primary" @click="onClickAdd">
            去下个单
          </NButton>
        </div> -->
        <div>
          <n-input-group>
              <n-input clearable v-model:value="params.keyword" placeholder="请输入订单关键词" :style="{ width: '100%' }" />
              <n-button @click="List" type="primary" ghost>
                搜索
              </n-button>
            </n-input-group>
        </div>
      </div>
    </n-card>
    <div class="box" :style="'height:'+innerHeights">
       <!-- 数据表 -->
      <div class="table-box">
     
          <n-data-table
            :loading="messageParams.loading"
            ref="table"
            :columns="columns"
            :data="data"
            :scroll-x="1800"
            :max-height="650"
          />
     
       
      </div> 
    </div>
     <div class="pagination">
            <div>共{{pagination.total}}条数据</div>
            <div>
              <n-pagination
              :page="params.pageNum"
                :page-size="params.pageSize"
                :item-count="pagination.total"
                size="medium"
                show-size-picker
                :page-slot="8"
                :page-sizes="pageSizes"
                :on-update:page="pageNext"
                :on-update:page-size="sizeNext"
            />
            </div>
        </div>

   <n-modal  v-model:show="showModal"
      :mask-closable="false"
      preset="dialog"
      :title="popTitle"
      content="你确认?"
      positive-text="确认"
      negative-text="算了"
      @positive-click="submitCallback"
      @negative-click="cancelCallback"
      >
      <div class="box-modal">
         <n-form
          ref="formRef"
          :model="formValue"
          :rules="rules"
        >
          <n-form-item label="订单状态">
            <n-select
              
                v-model:value="formValue.payStatus"
                  :style="{ width: '300px' }" 
                  filterable 
                  placeholder="请选订单类型"
                  :options="payStatusList"
                  clearable
                />
          </n-form-item>
      
      
        </n-form>
      </div>
  </n-modal>

  <n-modal  v-model:show="uploadShow"
      :mask-closable="false"
      preset="dialog"
      style="width: 1000px;"
      :title="'文件管理'"
      content="你确认?"
      positive-text="确定"
      negative-text="关闭"      
      @positive-click="uploadShow=false"
      @negative-click="uploadShow=false"
      >
      <div class="box-upload">
         <Upload type="1" @selectImage="selectImageFun"/>
      </div>
  </n-modal>
    
  </div>
</template>

<script setup lang="ts">
import { NAvatar, NButton, NImage, NSwitch, NTag  } from 'naive-ui'
import type { FormInst } from 'naive-ui'
import { nextTick, onMounted, ref } from 'vue'
import { Https,setPagination } from "@/utils"
import api from './api'
import Upload from "@/views/upload/index.vue"
const router = useRouter()
// const route = useRoute()

const innerHeights = ref(0);
onMounted(() => {
  innerHeights.value = String(window.innerHeight - 280)+'px'
  storeList()
  List() 
})

const payStatusList = ref([
  {
    label:'待支付',
    value:1
  },
  {
    label:'支付中',
    value:2
  },{
    label:'已支付',
    value:3
  },{
    label:'待发货',
    value:4
  },
  {
    label:'已发货',
    value:5
  },
  {
    label:'待收货',
    value:6
  },
  {
    label:'已收货',
    value:7
  },
  {
    label:'已退款',
    value:8
  },
])

function handleUpdateValue(value: string) {
    if(value){
      formValue.value.status = true
      $message.success("启用")
    }else{
      $message.error("禁用")
      formValue.value.status = false
    }
    
  }

const pageSizes = [
  {
    label: '10 每页',
    value: 10
  },
  {
    label: '20 每页',
    value: 20
  },
  {
    label: '30 每页',
    value: 30
  },
  {
    label: '40 每页',
    value: 40
  }
]


const pagination = ref({
  total:10
  
})
const formRef = ref<FormInst | null>(null);

const showModal = ref(false);
const uploadShow = ref(false);
const popTitle = ref('添加商品分类');
const params = ref({
  pageNum: 1,
  pageSize: 10,
  keyword: '',
})
const messageParams: any = ref({
  show: false,
  status: '403',
  loading: true,
})

const messageList: any = ref([
  {
    status: '500',
    title: '500 服务器错误',
    description: '服务器出错可能说明该雇更多程序员了',
    button: '散财消灾',
  },
  {
    status: '404',
    title: '404 资源不存在',
    description: '生活总归带点荒谬',
    button: '找点乐子吧',
  },
  {
    status: '403',
    title: '403 禁止访问',
    description: '总有些门是对你关闭的',
    button: '放轻松',
  },
])

const formValue = ref({
  businessId:"1",
  categoryDesc:"",
  categoryName:"",
  image:"",
  status:true,
  pid:0
})



// const pagination = { pageSize: 10 ,page:1}
// {
//     label: () => h('span', { style: { color: 'red' } }, '删除'),
//     key: 'delete'
//   }

const rules = {

  categoryDesc: {
    required: false,
    message: '请填写商品分类描述',
    trigger: 'blur'
  },
  categoryName: {
    required: true,
    message: '请填写商品分类名称',
    trigger: ['input']
  },

  image: {
    required: true,
    message: '请上传商品分类图片(支持url链接)',
    trigger: ['input']
  },
 
}


const columns = [
  
  {
    title: '订单ID',
    key: 'order_id',
    ellipsis: {
      tooltip: true
    },
    fixed: 'left'
  },
  {
    title: '店铺名称',
    ellipsis: {
      tooltip: true
    },
    fixed: 'left',
    render:(item)=> setStore(item)
 
  },
  {
    title: '商品名称',
    key: 'goodsName',
    ellipsis: {
      tooltip: true
    },
    fixed: 'left'
   
  },
 
  {
    title: '商品封面',

    
    render: ({ previewUrl }) => {
      // console.log(image)
      return h(NImage, {
        width: 60,
        src:Https()+previewUrl,
      })
    },

  },
  {
    title: '实际支付',
    key: 'total_money',
    ellipsis: {
      tooltip: true
    },
    render:(item)=> setPrice1(item)
  },
  {
    title: '商品金额',
    key: 'goods_money',
    ellipsis: {
      tooltip: true
    },
    render:(item)=> setPrice(item)
  },
  {
    title: '用户openid',
    key: 'wechat_openid',
    ellipsis: {
      tooltip: true
    },
    
  },
  {
    title: '用户手机号',
    key: 'wechatphone',
    ellipsis: {
      tooltip: true
    },
  render:(item)=> setUserInfo(item,'phone')
  },
  {
    title: '用户名称',
     
    ellipsis: {
      tooltip: true
    },
    render:(item)=> setUserInfo(item,'nickName')
   
  },
  {
    title: '订单类型',
    key: 'order_type',
    ellipsis: {
      tooltip: true
    },
   
    render:(item)=> setOrder_type(item)
  },
  {
    title: '订单状态',
    ellipsis: {
      tooltip: true
    },
   
    render:(item)=> setPayStatus(item)
  },
  {
    title: '支付类型',
    key: 'paypal_type',
    ellipsis: {
      tooltip: true
    },
    
    render:(item)=> setPaypal_type(item)
  },
  {
    title: '支付时间',
   ellipsis: {
      tooltip: true
    },
    key: 'utime',
    
  },
  {
    title: '下单时间',
    ellipsis: {
      tooltip: true
    },
    key: 'ctime',
   
  },
  {
    title: '操作',
    key: 'actions',
    width: 300,
    align: 'right',
    fixed: 'right',
 
    render(row) {
      return [
        h(
          NButton,
          {
            size: 'small',
            type: 'primary',
            secondary: true,
            onClick: () => handleDetails(row),
          },
          {
            default: () => '详情',
            icon: () => h('i', { class: 'i-fe:airplay' }),
          },
        ),

        h(
          NButton,
          {
            size: 'small',
            type: 'primary',
            style: 'margin-left: 12px;',
            secondary: true,
            onClick: () => handleOpenRolesSet(row),
          },
          {
            default: () => '编辑',
            icon: () => h('i', { class: 'i-fe:database' }),
          },
        ),

        h(
          NButton,
          {
            size: 'small',
            type: 'error',
            style: 'margin-left: 12px;',
            onClick: () => handleDelete(row.id),
          },
          {
            default: () => '删除',
            icon: () => h('i', { class: 'i-material-symbols:delete-outline text-14' }),
          },
        ),
      ]
    },
  },

]
const data: any = ref([])

const setUserInfo = (item,type) =>{
  const userInfo = JSON.parse(item.user_info)
  if(userInfo){
    return userInfo[type]
  }
  
}
const setPrice = (item) =>{
  console.log(item)
  if(item.goods_sku){
    
    return h('div', { style:{color:'red'} },`￥${JSON.parse(item.goods_sku).skuPrice}`)
  }else {
   return h('div', { style:{color:'red'} },`￥${JSON.parse(item.goods_info).goodsPrice}`)
  } 
}
const setPrice1 = (item) =>{
  console.log(item)
  // 订单类型，1普通订单，2月卡订单，3补录订单
  const goods = JSON.parse(item.goods_info)
  if(goods.goodsSkuType == '单规格'){
    if(item.payStatus == 1 || item.payStatus == 0 || item.payStatus==2){
      return h('div', { style:{color:'red'} },`无支付`)
    }else
    return h('div', { style:{color:'red'} },`￥${item.total_money}`)
  }
    
  else{
    if(item.payStatus == 1|| item.payStatus == 0 || item.payStatus==2){
      return '0'
    }else
    return JSON.parse(item.goods_sku).skuPrice
  }
   
}
const setOrder_type = (item) =>{
  // 订单类型，1普通订单，2月卡订单，3补录订单
  if(item.order_type == '1'){
    return '普通订单'
  }else if(item.order_type == '2'){
    return '月卡支付'
  }else if(item.order_type == '3'){
    return '补录订单'
  }else if(item.order_type == '4'){
    return '积分订单'
  }else if(item.order_type == '5'){
    return '余额订单'
  }
}

const setPayStatus = (item) =>{
  // 订单类型，1普通订单，2月卡订单，3补录订单
  if(item.payStatus == 1){
    return '确认支付'
  }else if(item.payStatus == 2){
    return '支付中'
  }else if(item.payStatus == 3){
    return '已支付'
  }else if(item.payStatus == 4){
    return '已退款'
  }else if(item.payStatus == 5){
    return '待发货'
  }else if(item.payStatus == 6){
    return '已发货'
  }else if(item.payStatus == 7){
    return '待收货'
  }else if(item.payStatus == 8){
    return '已发货'
  }else if(item.payStatus == 0){
    return '待支付'
  }
}


const setPaypal_type = (item) =>{
  // 订单类型，1普通订单，2月卡订单，3补录订单
  if(item.paypal_type == '1'){
    return '微信支付'
  }else if(item.paypal_type == '2'){
    return '支付宝支付'
  }else if(item.paypal_type == '3'){
    return '余额支付'
  }else if(item.paypal_type == '4'){
    return '月卡支付'
  }
}

const setStore = (item) =>{
  for (let index = 0; index < storeOptions.value.length; index++) {
    if(storeOptions.value[index].value == item.business_id){
      return storeOptions.value[index].label
       
    }
  }
}

const handleDetails = (item) =>{
  router.push({
    path:'/order/details',
    query:{
      id:item.id
    }
  })
}

async function handleDelete(id){
  const res: any = await api.DeleteApi({
    id:id
  })

  if(res.code == 200){
    List();
    $message.success('删除成功!')
  }else{
    
  }

}
const storeOptions = ref([])
async function storeList() {
    const res: any = await api.storeListApi({
      pageNum:1,
      pageSize:300
    })
    if (res.code == 200) {
      storeOptions.value = res.data.list.map(item=>{
        return{
          label:item.businessName,
          value:item.businessId
        }
      })
    }
    
}

const handleOpenRolesSet =(item) =>{
  formValue.value = item;
  popTitle.value = '编辑';
  showModal.value = true;
} 

const selectImageFun =(selectImageList) =>{
  formValue.value.image = selectImageList[0];  // 只获取第一张图
  uploadShow.value =false
} 


async function List() {
  try {
    messageParams.value.loading = true
    const res: any = await api.ListApi(params.value)
    if (res.code == 200) {
      messageParams.value.loading = false
      pagination.value.total = res.data.total
      data.value = res.data.list
    }
    else {
      messageParams.value.show = false
      messageParams.value.status = '500'
    }
  }
  catch (error) {
    console.error(error)
  }
}
function onClickAdd(){
  popTitle.value = '添加商品分类'
  showModal.value = true
}
async function submitCallback() {
  messageParams.value.loading = true
  formRef.value?.validate((errors) => {
    if (!errors) {
      if(popTitle.value == '添加商品分类')
        categoryAddFun();
      else
        categoryEditFun();
    }
    else {
      showModal.value = true
      return 
 
    }
  })
}

async function categoryAddFun(){
  const res: any = await api.categoryAddApi(formValue.value)
  if(res.code == 200){
    List();
    
    $message.success('添加成功!')
  }else{
    $message.error(res.message)
  }
}

async function categoryEditFun(){
  const res: any = await api.EditApi({
    id:formValue.value.id,
    payStatus:formValue.value.payStatus,
    order_id:formValue.value.order_id
  })
  if(res.code == 200){
    List();
    $message.success('编辑成功!')
  }else{
    $message.error(res.message)
  }
}

function pageNext(page){
  params.value.pageNum = page
  List();
}
function sizeNext(size){
  params.value.pageNum = 1
  params.value.pageSize = size
  List();
}


function cancelCallback() {
  
  List();
  showModal.value = false
}
</script>

<style scoped>
 .box {
    height: 75vh;
    overflow-y: auto;
}
.table-box{
  padding: 20px;
}
.box-modal{
  width: 400px;
  /* height: 350px; */
  /* overflow-y: auto; */
}
.pagination{
  display: flex;
  justify-content: right;
  /* height: 60px; */
  gap: 10px;
  align-items: center;
  position: relative;
  top: 20px;
  right:30px;
}
.header{
  display: flex;gap: 10px;
}
.box-upload{
  /* width: 1000px; */
  height: 650px;
  width: 100%;
  /* background: white; */
}
.imageUpload{
  width:100px;
  height:100px;
  border:1px solid #eee;
  display: flex;
  justify-content: center;
  border-radius: 6px;
  align-items: center;
}
.imageUpload:hover{
  border:1px solid rgb(49, 108, 114);
}
</style>
